package com.ldl.distributelock.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class ZkTest {
    public static void main(String[] args) throws InterruptedException {
        ZooKeeper zooKeeper = null;
        CountDownLatch countDownLatch = new CountDownLatch(1);
        try {
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 30000, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    Event.KeeperState state = watchedEvent.getState();
                    if (Event.KeeperState.SyncConnected.equals(state)&&Event.EventType.None.equals(watchedEvent.getType())) {
                        System.out.println("获取连接了吗" + watchedEvent);
                        countDownLatch.countDown();
                    } else if (Event.KeeperState.Closed.equals(state)) {
                        System.out.println("关闭连接");
                    }
                }
            });
            countDownLatch.await();
            System.out.println("一顿操作");
            //节点新增：永久化 永久序列化  临时 临时序列化
//            zooKeeper.create("/ldl","hello test1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
//            zooKeeper.create("/ldl","hello test1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
//            zooKeeper.create("/ldl","hello test1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
//            zooKeeper.create("/ldl","hello test1".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            //查询 判断节点是否存在
            Stat stat = zooKeeper.exists("/ldl", false);

            //判断节点是否存在
            if (stat != null) {
                System.out.println("当前节点存在");
            } else {
                System.out.println("当前节点不存在");
            }

            //获取节点内容
            byte[] data = zooKeeper.getData("/ldl", false, stat);
            System.out.println("当前节点内容" + new String(data));

            //获取子节点
//            System.out.println(zooKeeper.getChildren("/ldl", false));
            System.out.println(zooKeeper.getChildren("/ldl", new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    System.out.println("节点的子节点变化。。。。");
                }
            }));

            //更新必须设置版本号  版本号不一致会更新失败  -1代表不关心版本号
            zooKeeper.setData("/ldl", "wwaawewa".getBytes(), stat.getVersion());

//            zooKeeper.delete("/ldl/test1", -1);

            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zooKeeper != null) {
                zooKeeper.close();
            }
        }
    }
}
